import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import ReactDOM from 'react-dom';
import withRedux from 'next-redux-wrapper';
import { NavBar, Carousel } from 'antd-mobile';
import Router from 'next/router';
import Content from '../views/common/Content';
import initStore from '../store/initStore';
import { asyncGetHomeNewsListAction, setScrollerPositionAction, asyncGetHomeWeatherAction, increaseNewsClickCount } from '../store/actions/homeAction';
import SysUtil from '../core/utils/SysUtil';
import '../core/utils/DateUtil';

class HomeScreen extends PureComponent
{
    static getInitialProps({ store, isServer })
    {
        if(!isServer)
        {
            return {};
        }
        return store.dispatch(asyncGetHomeNewsListAction()).then(()=>{
            return store.dispatch(asyncGetHomeWeatherAction(isServer));
        }).then(()=>{
            return {
            };
        });
    }
    componentWillUnmount()
    {
        this.cacheScrollViewPosition();
    }
    componentDidMount() 
    {
        if(!this.props.news)
        {
            this.props.dispatch(asyncGetHomeNewsListAction()).then(()=>{
                this.props.dispatch(asyncGetHomeWeatherAction(false));
            })
        }
        this.restoreScrollViewPosition();
        this.showScenicList = this.showScenicList.bind(this);
        this.showMoreNews = this.showMoreNews.bind(this);
    }
    componentDidUpdate(prevProps, prevState, snapshot)
    {
        if (this.props.isUserLogined && this.props.isUserLogined !== prevProps.isUserLogined) 
        {
            console.log('登录成功!');
        }
    }
    render() {
        return (
            <div>
                <NavBar mode='dark' 
                    className='navBar'
                    leftContent={<img className='homeMine' src={require('../assets/images/home/mine.png')} alt=''/>}
                    rightContent={<div className='homeSign'>签到</div>}
                    onLeftClick={this.showMyProfile}>
                    <img className='homeLogo' src={require('../assets/images/home/logo.png')} alt=''/>
                </NavBar>
                <Content ref={(view) => { this.scrollView = view ? view.getWrappedInstance() : this.scrollView; }}>
                    {
                        this.renderHeaderBannerView()
                    }
                    {
                        this.renderWeather()
                    }
                    {
                        this.renderStartLeave()
                    }
                    <div className='homeSplitSpace'></div>
                    {
                        this.renderNewsView()
                    }
                    {
                        this.renderPlay()
                    }
                    {
                        this.renderBottomViews()
                    }
                    {
                        this.renderMapViews()
                    }
                </Content>
                <style jsx global>{`
                    .homeLogo {
                      height: 25px; }

                    .homeMine {
                      width: 20px; }

                    .homeSplitSpace {
                      height: 5px; }

                    .homeSign {
                      margin-right: -15px;
                      background: #f3dad8;
                      height: 30px;
                      padding: 0px 12px 0px 14px;
                      border-radius: 20px 0 0 20px;
                      color: #c5443e;
                      box-shadow: 2px 3px 4px rgba(106, 5, 0, 0.3);
                      font-size: 14px;
                      line-height: 30px;
                      font-weight: 300; }

                `}</style>
            </div>
        );
    }
    renderHeaderBannerView()
    {
        let banners = [
            {
                image: require('../assets/images/home/banner-1.jpg'),
                path: '/scenic/list'
            },
            {
                image: require('../assets/images/home/banner-2.jpg'),
                path: '/traffic'
            },
            {
                image: require('../assets/images/home/banner-3.jpg'),
                path: '/overview'
            }
        ];
        return (
            <Carousel
                className='homeBanner'
                autoplay={true}
                dots={true}
                swiping={true}
                infinite
                selectedIndex={0}
                swipeSpeed={35}>
                {
                    banners.map((item, index)=><div key={index} className='homeBannerItem' style={{backgroundImage: `url(${item.image})`}}/>)
                }
                <style jsx global>{`
                    .homeBanner {
                        height: 187px !important; }
  
                    .homeBannerItem {
                        width: 100%;
                        height: 187px !important;
                        background-position: center;
                        background-size: cover;
                        background-repeat: no-repeat; }
                `}</style>
            </Carousel>
        );
    }
    hasNews() 
    {
        return !(!this.props.news || !this.props.news.dataList || this.props.news.dataList.length === 0);
    }
    renderNewsView() 
    {
        if (!this.hasNews()) 
        {
            return null;
        }
        return (
            <div className='homeNewsBox'>
                <div className='homeNewsHeader' onClick={this.showMoreNews}>
                    <div className='homeNewsIcon'/>
                    <div className='homeNewsTitle'>旅游动态</div>
                    <div style={{flex: 1}}/>
                    <div className='homeNewsMore'>更多</div>
                </div>
                {
                    this.props.news.dataList.map((item, index)=>this.renderNewsItemView(item, index, index === this.props.news.dataList.length - 1))
                }
                <style jsx>{`
                    .homeNewsHeader {
                        display: flex;
                        flex-direction: row;
                        height: 35px;
                        align-items: center;
                        border-bottom: 1px #dddddd solid; }

                    .homeNewsIcon {
                        width: 3px;
                        height: 18px;
                        background-color: #c5443e;
                        margin-left: 6px;
                        margin-right: 6px; }

                    .homeNewsTitle {
                        font-size: 16px;
                        font-weight: 500;
                        color: #333333; }

                    .homeNewsMore {
                        font-size: 14px;
                        font-weight: 300;
                        color: #999999;
                        margin-right: 10px; }
                `}</style>
            </div>
        );
    }
    renderNewsItemView(item, index, isLast)
    {
        let imgUrl = item.F_MiddleImage;
        let date = item.CreateDate;
        date = date ? (date.split(' ')[0]) : date;
        return (
            <div className={isLast ? 'newsListItem' : 'newsListItem newsListItemSplit'} key={index}>
                <div style={{backgroundImage: `url(${imgUrl})`}} className='scenicListItemImg'/>
                <div className='newsListItemTextBox'>
                    <div className='scenicListItemName'>{item.Head}</div>
                    <div className='newsListSecondRow'>
                        <img className='newsListIcon' src={require('../assets/images/time.png')} alt=''/>
                        <div className='newsListItemOthers'>{date}</div>
                        <div style={{flex: 1}}/>
                        <img className='newsListIcon' src={require('../assets/images/eye.png')} alt=''/>
                        <div className='newsListItemOthers'>{item.ClickCount}</div>
                    </div>
                </div>
                <style jsx>{`
                    .newsListItem{
                        display: flex;
                        flex-direction: row;
                        padding: 10px;
                    }
                    .newsListItemSplit{
                        border-bottom: 1px #dddddd solid;
                    }
                    .scenicListItemImg{
                        position: relative;
                        flex: 1;
                        background-position: center;
                        background-size: cover;
                        background-repeat: no-repeat;
                    }
                    .newsListItemTextBox{
                        margin-left: 10px;
                        display: flex;
                        flex-direction: column;
                        flex: 1.5;
                        justify-content: space-between;
                        min-height: 85px;
                    }
                    .scenicListItemName{
                        font-size: 14px;
                        color: #333333;
                        font-weight: 400;
                    }
                    .newsListSecondRow{
                        display: flex;
                        flex-direction: row;
                        align-items: center;
                        margin-top: 15px;
                    }
                    .newsListIcon{
                        width: 18px;
                    }

                    .newsListItemOthers{
                        color: #999999;
                        font-size: 14px;
                        font-weight: 300;
                        text-align: center;
                        margin-left: 3px;
                    }
                `}</style>
            </div>
        );
    }
    renderTitle(title) 
    {
        return (
            <div className='startLeaveTitleRow'>
                <div style={{ flex: 1 }} />
                <img src={require('../assets/images/home/ico-title.png')} alt='' />
                <span className='startLeaveTitle'>{title}</span>
                <img src={require('../assets/images/home/ico-title.png')} alt='' />
                <div style={{ flex: 1 }} />
                <style jsx>{`
                    .startLeaveTitleRow {
                        display: flex;
                        flex-direction: row;
                        height: 44px;
                        align-items: center;
                        margin-top: 25px; }
  
                      .startLeaveTitleRow img {
                        width: 10px;
                        height: 10px; }
  
                      .startLeaveTitle {
                        font-size: 1.0em;
                        color: #333333;
                        font-weight: 700;
                        margin-left: 10px;
                        margin-right: 10px; }
                `}</style>
            </div>
        );
    }
    //首页天气
    renderWeather(){
        if(!this.props.weather){
            return;
        }
        let pm25Text='优';
        let pm25=this.props.weather.pm25;
        if (pm25 >= 0 && pm25 <= 50) {
            pm25Text = '优';
        }
        else if (pm25 >= 51 && pm25 <= 100) {
            pm25Text = '良';
        }
        else if (pm25 >= 101 && pm25 <= 150) {
            pm25Text = '轻度污染';
        }
        else if (pm25 >= 151 && pm25 <= 200) {
            pm25Text = '中度污染';
        }
        else if (pm25 >= 201 && pm25 <= 300) {
            pm25Text = '重度污染';
        }
        else {
            pm25Text = '严重污染';
        }
        return(
            <div className='homeWeatherBox'>
                <div className='homeWeatherIcon' style={{backgroundImage:`url(${this.getWeatherIcon(this.props.weather.weather_data[0].dayPictureUrl)})`}}></div>
                <div className='homeWeatherTempText'>{this.props.weather.weather_data[0].weather}</div>
                <div className='homeWeatherDateText'>{new Date().formatDate('YYYY-MM-DD')}</div>
                <div className='homeWeatherAqiText'>
                    空气质量:{pm25Text}
                </div>
                <style jsx>{`
                    .homeWeatherBox {
                        width: 100%;
                        height: 25px;
                        background-color: #b4aead;
                        color: #fff;
                        z-index: 10;
                        position: absolute; }
  
                    .homeWeatherIcon {
                        background-position: center;
                        background-repeat: no-repeat;
                        background-size: 100%;
                        width: 18%;
                        height: 80px;
                        float: left;
                        margin-top: -40px;
                        margin-left: 10px; }

                    .homeWeatherTempText {
                        font-size: 14px;
                        float: left;
                        width: 16%;
                        text-align: center;
                        line-height: 25px; }

                    .homeWeatherDateText {
                        font-size: 12px;
                        float: left;
                        border-right: 1px solid #eee;
                        border-left: 1px solid #eee;
                        padding: 0 10px;
                        height: 73%;
                        margin: 0 10px;
                        width: 20%;
                        text-align: center;
                        margin-top: 5px; }

                    .homeWeatherAqiText {
                        font-size: 12px;
                        padding-left: 15px;
                        text-align: center;
                        line-height: 25px; }  
                `}</style>
            </div>
        );
    }
    //获取本地天气图标
    getWeatherIcon(day){
        let dic = [
            { key: 'qing', value: require('../assets/images/weather/0.png') }, //晴
            { key: 'yin', value: require('../assets/images/weather/1.png') }, //阴
            { key: 'duoyun', value: require('../assets/images/weather/2.png') }, //多云
            { key: 'wu', value: require('../assets/images/weather/18.png') }, //雾
            { key: 'mai', value: require('../assets/images/weather/53.png') }, //霾
            { key: 'fuchen', value: require('../assets/images/weather/29.png') }, //浮尘
            { key: 'yangsha', value: require('../assets/images/weather/30.png') }, //扬沙
            { key: 'shachenbao', value: require('../assets/images/weather/20.png') }, //沙尘暴
            { key: 'qiangshachenbao', value: require('../assets/images/weather/31.png') }, //强沙尘暴
            { key: 'zhenyu', value: require('../assets/images/weather/3.png') }, //阵雨
            { key: 'leizhenyu', value: require('../assets/images/weather/4.png') }, //雷阵雨
            { key: 'leizhenyubanyoubingbao', value: require('../assets/images/weather/5.png') }, //雷阵雨伴有冰雹
            { key: 'xiaoyu', value: require('../assets/images/weather/7.png') }, //小雨
            { key: 'xiaoyuzhuanzhongyu', value: require('../assets/images/weather/8.png') }, //小雨转中雨
            { key: 'zhongyu', value: require('../assets/images/weather/8.png') }, //中雨
            { key: 'zhongyuzhuandayu', value: require('../assets/images/weather/9.png') }, //中雨转大雨
            { key: 'dayu', value: require('../assets/images/weather/9.png') }, //大雨
            { key: 'dayuzhuanbaoyu', value: require('../assets/images/weather/10.png') }, //大雨转暴雨
            { key: 'baoyu', value: require('../assets/images/weather/10.png') },  //暴雨
            { key: 'baoyuzhuandabaoyu', value: require('../assets/images/weather/11.png') }, //暴雨转大暴雨
            { key: 'dabaoyu', value: require('../assets/images/weather/11.png') }, //大暴雨          
            { key: 'dabaoyuzhuantedabaoyu', value: require('../assets/images/weather/12.png') }, //大暴雨转特大暴雨
            { key: 'tedabaoyu', value: require('../assets/images/weather/12.png') }, //特大暴雨
            { key: 'dongyu', value: require('../assets/images/weather/19.png') }, //冻雨
            { key: 'yujiaxue', value: require('../assets/images/weather/6.png') }, //雨夹雪
            { key: 'zhenxue', value: require('../assets/images/weather/13.png') }, //阵雪
            { key: 'xiaoxue', value: require('../assets/images/weather/14.png') }, //小雪
            { key: 'xiaoxuezhuanzhongxue', value: require('../assets/images/weather/15.png') }, //小雪转中雪
            { key: 'zhongxue', value: require('../assets/images/weather/15.png') }, //中雪
            { key: 'zhongxuezhuandaxue', value: require('../assets/images/weather/16.png') }, //中雪转大雪
            { key: 'daxue', value: require('../assets/images/weather/16.png') }, //大雪
            { key: 'daxuezhuanbaoxue', value: require('../assets/images/weather/17.png')}, //大雪转暴雪
            { key: 'baoxue', value: require('../assets/images/weather/17.png') }, //暴雪          
        ];

        let result = day;
        if (result && result !== null && result !== '') {
            for (let i = 0; i < dic.length; i++) {
                if (result.indexOf(dic[i].key) > -1) {
                    result = dic[i].value;
                    break;
                }
            }
        }
        return result;
    }
    isBrowser()
    {
        return typeof window !== 'undefined';
    }
    // 开始出发
    renderStartLeave() 
    {
        let hmargin = 8;
        let rowWidth = this.isBrowser() ? (window.innerWidth - 10 * 2) : 320;
        let rightWidth = (rowWidth - 3 * hmargin) / 4.0;
        let secondLineItemWidth = (rowWidth - 2 * hmargin - rightWidth) / 2.0;
        let redItemHeight = 101.0 * rightWidth / 175.0;
        let secondLineHeight = 111.0 * secondLineItemWidth / 264.0;
        let rightHeight = redItemHeight + secondLineHeight + hmargin;
        return (
            <div>
                {
                    this.renderTitle('了解禹州')
                }
                <div className='startLeaveMenuBox'>
                    <div className='startLeaveMenuLeftRow'>
                        <div className='startLeaveMenuRow'>
                            <div className='startLeaveMenuItem'
                                onClick={this.showScenicList}
                                style={{width: rightWidth + 'px', height: redItemHeight + 'px'}}>
                                <img src={require('../assets/images/home/index-hot-scenic.png')} alt='' />
                            </div>
                            <div style={{ width: '8px' }} />
                            <div className='startLeaveMenuItem'
                                style={{width: rightWidth + 'px', height: redItemHeight + 'px'}}>
                                <img src={require('../assets/images/home/index-rec-hotel.png')} alt='' />
                            </div>
                            <div style={{ width: '8px' }} />
                            <div className='startLeaveMenuItem'
                                style={{width: rightWidth + 'px', height: redItemHeight + 'px'}}>
                                <img src={require('../assets/images/home/index-line.png')} alt='' />
                            </div>
                        </div>
                        <div className='startLeaveMenuRow'>
                            <div className='startLeaveMenuItem'
                                style={{width: secondLineItemWidth + 'px', height: secondLineHeight + 'px'}}>
                                <img src={require('../assets/images/home/index-happy-amusement.png')} alt='' />
                            </div>
                            <div style={{ width: '8px' }} />
                            <div className='startLeaveMenuItem'
                                style={{width: secondLineItemWidth + 'px', height: secondLineHeight + 'px'}}>
                                <img src={require('../assets/images/home/index-life-service.png')} alt='' />
                            </div>
                        </div>
                    </div>
                    <div className='startLeaveMenuRightRow'>
                        <div style={{ width: '8px' }} />
                        <div className='startLeaveMenuItem'
                            style={{width: rightWidth + 'px', height: rightHeight + 'px'}}>
                            <img src={require('../assets/images/home/index-activity.png')} alt=''/>
                        </div>
                    </div>
                </div>
                <style jsx>{`
                    .startLeaveMenuBox {
                        margin-left: 10px;
                        margin-right: 10px;
                        display: flex;
                        flex-direction: row; }
  
                      .startLeaveMenuBox .startLeaveMenuLeftRow {
                        flex: 3; }
  
                      .startLeaveMenuBox .startLeaveMenuRightRow {
                        flex: 1;
                        display: flex;
                        flex-direction: row; }
  
                      .startLeaveMenuBox .startLeaveMenuLeftRow .startLeaveMenuRow {
                        display: flex;
                        flex-direction: row;
                        align-items: center;
                        margin-bottom: 8px; }
  
                      .startLeaveMenuBox .startLeaveMenuLeftRow .startLeaveMenuRow .startLeaveMenuItem {
                        display: flex;
                        flex-direction: row;
                        align-items: center;
                        justify-content: center; }
  
                      .startLeaveMenuItem img {
                        width: 100%;
                        height: 100%; }
  
                      .startLeaveMenuRightRow img {
                        width: 100%;
                        height: 100%; }
                `}</style>
            </div>
        );
    }
    // 玩转
    renderPlay() 
    {
        let menus = [
            {
                icon: require('../assets/images/home/scenic.png'),
                title: '景点',
                pathname: '/scenic/recommend-list',
            }, {
                icon: require('../assets/images/home/food.png'),
                title: '美食',
                pathname: '/food/recommend-list',
            }, {
                icon: require('../assets/images/home/stay.png'),
                title: '住宿',
                pathname: '/hotel/recommend-list'
            }, {
                icon: require('../assets/images/home/photo-4.png'),
                title: '交通',
                pathname: '/traffic',
            }, {
                icon: require('../assets/images/home/photo-5.png'),
                title: '特产',
                pathname: '/specialty/recommend-list',
            }, {
                icon: require('../assets/images/home/photo-6.png'),
                title: '娱乐',
                pathname: '/fun/recommend-list',
            }, {
                icon: require('../assets/images/home/index-shopping.png'),
                title: '购物',
                pathname: '/shopping/recommend-list',
            }, /*{
                icon: require('../assets/images/home/index-farmhouse.png'),
                title: '乡村游',
                pathname: '/farm-house/list',
            },*/ {
                icon: require('../assets/images/home/index-travelagent.png'),
                title: '旅行社',
                pathname: '/travel-agent/list',
            }, /*{
                icon: require('../assets/images/home/photo-7.png'),
                title: '攻略',
                pathname: '/strategy/list',
            }, */
        ];
        return (
            <div>
                {
                    this.renderTitle('玩转禹州')
                }
                <div className='homePlayMenuRow'
                    ref={(div)=>{this.playDiv = div;}}>
                    {
                        menus.map((item, index) => <div key={index} 
                            className='homePlayMenuItem'>
                            <img src={item.icon} alt='' />
                            <span>{item.title}</span>
                        </div>)
                    }
                </div>
                <div className='homePlaySplit' />
                <style jsx>{`
                    .homePlayMenuRow {
                        display: flex;
                        display: -webkit-box;
                        flex-direction: row;
                        margin-left: 10px;
                        overflow-x: scroll;
                        overflow-y: hidden; }
  
                      .homePlaySplit {
                        margin-top: 20px;
                        border-bottom: 1px #dddddd solid; }
  
                      .homePlayMenuRow::-webkit-scrollbar {
                        display: none; }
  
                      .homePlayMenuRow img {
                        width: 100px;
                        height: 120px; }
  
                      .homePlayMenuItem {
                        margin-right: 5px;
                        display: flex;
                        flex-direction: column;
                        align-items: center; }
  
                      .homePlayMenuItem span {
                        color: #666666;
                        font-size: 13px;
                        font-weight: 300;
                        margin-top: 5px; }  
                `}</style>
            </div>
        );
    }
    renderBottomViews() 
    {
        return (
            <div className='homeBottomBox'>
                <div style={{ display: 'flex', flexDirection: 'row' }}>
                    <div style={{ flex: 1 }}>
                        <img style={{ width: '100%' }} src={require('../assets/images/home/photo-11.jpg')} alt='' />
                    </div>
                    <div style={{ width: 5 }} />
                    <div style={{ flex: 1 }}>
                        <img style={{ width: '100%' }} src={require('../assets/images/home/photo-12.jpg')} alt='' />
                    </div>
                    <div style={{ width: 5 }} />
                    <div style={{ flex: 1 }}>
                        <img style={{ width: '100%' }} src={require('../assets/images/home/photo-13.jpg')} alt='' />
                    </div>
                </div>
                <style jsx>{`
                    .homeBottomBox {
                        margin: 10px; }
                `}</style>
            </div>
        );
    }
    renderMapViews()
    {
        return (
            <div style={{ padding:10, paddingTop: 0}}>
                <img style={{width:'100%'}} src={require('../assets/images/home/map.jpg')} alt='' />
            </div>
        );
    }
    cacheScrollViewPosition()
    {
        let offset = this.scrollView.getOffsetY();
        let playOffset = ReactDOM.findDOMNode(this.playDiv).scrollLeft;
        this.props.dispatch(setScrollerPositionAction(offset, playOffset));
    }
    restoreScrollViewPosition() 
    {
        if (this.scrollView) 
        {
            if (!isNaN(this.props.scrollViewOffset)) 
            {
                this.scrollView.scrollToY(this.props.scrollViewOffset);
            }
            else 
            {
                this.scrollView.scrollToY(0);
            }
        }
        if(this.playDiv)
        {
            if (!isNaN(this.props.playScrollViewOffset)) 
            {
                // ReactDOM.findDOMNode(this.playDiv).scrollTo(this.props.playScrollViewOffset, 0);
                ReactDOM.findDOMNode(this.playDiv).scrollLeft = this.props.playScrollViewOffset;
            }
            else 
            {
                // ReactDOM.findDOMNode(this.playDiv).scrollTo(0, 0);
                ReactDOM.findDOMNode(this.playDiv).scrollLeft = 0;
            }
        }
    }
    showScenicList() 
    {
        Router.push('/scenic/list')
    }
    showMoreNews()
    {
        Router.push('/news/list')
    }
}

const mapStateToProps = function (state) {
    return {
        ...state.home,
        isUserLogined: SysUtil.isUserLogined(state),
    };
};

HomeScreen = withRedux(initStore, mapStateToProps)(HomeScreen);

export default HomeScreen;